<template>
  <!-- 添加项目的对话框 ********************************** -->
  <el-dialog
    title="添加项目"
    :visible.sync="editDialogVisible"
    width="80%"
    @close="handleProjectEditDialogClose"
    center
    class="projecteditDialog"
  >
    <span>
      <el-row :gutter="20">
        <el-col :span="14"
          ><div class="grid-content bg-purple">
            <el-form
              ref="projectEditFormRef"
              :model="projectEditForm"
              :rules="projectEditFormRules"
              label-width="120px"
              size="mini"
            >
              <el-form-item label="项目标题" prop="name">
                <el-input
                  placeholder="请输入项目名称"
                  v-model="projectEditForm.name"
                  prop="essayname"
                ></el-input>
              </el-form-item>
              <el-form-item label="项目编号" prop="no">
                <el-input
                  disabled
                  placeholder="请输入项目编号"
                  v-model="projectEditForm.no"
                ></el-input>
              </el-form-item>
              <el-form-item label="立项机构" prop="initiation_agency">
                <el-input
                  placeholder="请输入立项机构"
                  v-model="projectEditForm.initiation_agency"
                ></el-input>
              </el-form-item>
              <!-- 立项时间 -->
              <el-form-item label="立项时间" prop="initial_time">
                <el-col>
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="projectEditForm.initial_time"
                    style="width: 100%"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
              <!-- 结题时间 -->
              <el-form-item label="结题时间" prop="closing_time">
                <el-col>
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="projectEditForm.closing_time"
                    style="width: 100%"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
              <!-- 学科分类 -->
              <el-form-item label="学科分类" prop="subject_classification">
                <!-- options是数据 -->
                <el-cascader
                  placeholder="请选择学科分类"
                  v-model="subject_classificationVal"
                  :options="subject_classificationList"
                  :props="{ expandTrigger: 'hover' }"
                  value="label"
                  label="value"
                  @change="handleSubject_classificationChange"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="项目分类" prop="category">
                <el-input
                  placeholder="请输入项目分类"
                  v-model="projectEditForm.category"
                ></el-input>
              </el-form-item>
              <!-- 下达单位 -->
              <el-form-item label="下达单位" prop="release_unit">
                <!-- options是数据 -->
                <el-cascader
                  placeholder="请选择下达单位"
                  v-model="release_unitVal"
                  :options="collegeList"
                  :props="{ expandTrigger: 'hover' }"
                  @change="handleRelease_unitInputChange"
                ></el-cascader>
              </el-form-item>
              <!-- 结题时间 -->
              <el-form-item label="开始时间" prop="start_time">
                <el-col>
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="projectEditForm.start_time"
                    style="width: 100%"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
              <!-- 结束时间 -->
              <el-form-item label="结束时间" prop="end_time">
                <el-col>
                  <el-date-picker
                    type="date"
                    placeholder="选择日期"
                    v-model="projectEditForm.end_time"
                    style="width: 100%"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="摘要" prop="abstract">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="projectEditForm.abstract"
                >
                </el-input>
              </el-form-item>

              <el-form-item label="经费" prop="budget">
                <el-input
                  placeholder="请输入项目经费"
                  v-model="projectEditForm.budget"
                ></el-input>
              </el-form-item>
              <el-form-item label="主持人" prop="commander">
                <el-input
                  placeholder="请输入主持人"
                  @input="commanderInputChange"
                  v-model="projectEditForm.commander"
                ></el-input>
              </el-form-item>
              <el-form-item label="参与者" prop="participant">
                <el-input
                  placeholder="多名参与者请使用逗号隔开"
                  v-model="projectEditForm.participant"
                  @input="participantInputChange"
                ></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="remarks">
                <el-input
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                  v-model="projectEditForm.remarks"
                >
                </el-input>
              </el-form-item>
            </el-form></div
        ></el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-upload
              ref="projectfileUploadRef"
              class="projectUpload"
              :auto-upload="false"
              drag
              action="http://localhost:3000/project/edit/upload"
              method="post"
              :on-change="checkType"
              :on-success="uploadSuccess"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传.pdf文件，且不超过52mb
              </div>
            </el-upload>
          </div></el-col
        >
      </el-row>
    </span>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleProjectEditDialogConfirm"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "myEditProject",
  props: ["projectList"],
  data() {
    return {
      editDialogVisible: false,
      // 编辑项目数据
      projectEditForm: {
        // 项目名
        name: "",
        // 项目编号
        no: "",
        // 立项机构
        initiation_agency: "",
        // 立项时间
        initial_time: "",
        // 结题时间
        closing_time: "",
        // 下达单位
        release_unit: "",
        // 开始时间
        start_time: "",
        // 结束时间
        end_time: "",
        // 学科分类
        subject_classification: "",
        // 项目分类
        category: "",
        // 摘要
        abstract: "",
        // 经费
        budget: "",
        // 主持人
        commander: "",
        // 参与者
        participant: "",
        // 文件地址
        projectfile: "",
        // 留言
        remarks: "",
      },
      // 添加表单的验证规则对象
      projectEditFormRules: {
        name: [{ required: true, message: "请输入项目名", trigger: "blur" }],
        initation_agency: [
          { required: true, message: "请输入立项机构", trigger: "blur" },
        ],
        initial_time: [
          { required: true, message: "请输入立项时间", trigger: "blur" },
        ],
        closing_time: [
          { required: true, message: "请输入结题时间", trigger: "blur" },
        ],
        start_time: [
          { required: true, message: "请输入开始时间", trigger: "blur" },
        ],
        subject_classification: [
          { required: true, message: "请选择学科分类", trigger: "blur" },
        ],
        category: [
          { required: true, message: "请输入项目分类", trigger: "blur" },
        ],
        end_time: [
          { required: true, message: "请输入结束时间", trigger: "blur" },
        ],
        release_unit: [
          { required: true, message: "请输入项目分类", trigger: "blur" },
        ],
        abstract: [
          { required: true, message: "请输入项目简介", trigger: "blur" },
        ],
        budget: [
          { required: true, message: "请输入项目经费", trigger: "blur" },
        ],
        abstract: [
          { required: true, message: "请输入项目摘要", trigger: "blur" },
        ],
        commander: [
          { required: true, message: "请输入项目主持人", trigger: "blur" },
        ],
        participant: [
          { required: true, message: "请输入项目参与者", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请输入审核状态", trigger: "blur" },
        ],
        remarks: [{ required: false, message: "请输入备注", trigger: "blur" }],
      },
      // 学科分类
      subject_classificationVal: [],
      // 学院下达单位
      release_unitVal: [],
      isUploadFile: false,
    };
  },
  methods: {
    projectEditDialogVisibleShow(data) {
      this.editDialogVisible = !this.editDialogVisible;

      this.projectEditForm = data;
      // 同步学科分类
      try {
        let subject_classification = data.subject_classification.split("-");
        // console.log(subject_classification);
        this.subject_classificationList.forEach((item) => {
          if (item.label === subject_classification[0]) {
            item.children.forEach((child) => {
              if (child.label === subject_classification[1]) {
                this.subject_classificationVal = [item.value, child.value];
                throw new Error("forEach end");
              }
            });
          }
        });
      } catch (err) {}

      // 同步学院下达单位
      try {
        this.collegeList.forEach((item) => {
          if (item.label == data.release_unit) {
            this.release_unitVal[0] = item.value;
            throw new Error("forEach end");
          }
        });
      } catch (err) {}
      // console.log(formData);
    },
    handleProjectEditDialogClose() {},
    // 学科分类选择事件
    handleSubject_classificationChange(val) {
      this.subject_classificationList.forEach((item) => {
        if (item.value == val[0]) {
          item.children.forEach((child) => {
            if (child.value == val[1]) {
              this.$set(
                this.projectEditForm,
                "subject_classification",
                `${item.label}-${child.label}`
              );
            }
          });
        }
      });
    },
    // 下达单位选择事件
    handleRelease_unitInputChange(val) {
      // console.log(val);
      // console.log(this.release_unitVal);
      try {
        this.collegeList.forEach((item) => {
          if (item.value == val[0]) {
            this.$set(this.projectEditForm, "release_unit", item.label);
            throw new Error("EndForEach");
          }
        });
      } catch (err) {}
    },
    // 编辑表单确认上传
    handleProjectEditDialogConfirm() {
      this.$refs.projectEditFormRef.validate(async (valid) => {
        if (!valid) return;
        if (!this.isUploadFile) return this.$message.warning("请上传文件");
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$axios.post("/project/edit", {
          projectEditForm: this.projectEditForm,
        });

        if (res.status == 100) {
          return this.$refs.projectfileUploadRef.submit();
        } else {
          return this.$message.error(`${res.message}`);
        }
      });
    },
    // 项目上传检查
    checkType(file, fileList) {
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      fileList = [];

      if (fileType != "pdf") {
        this.$message.error("文件格式不正确");
        return false;
      }
      if (file.size / 1024 / 1024 > 52) {
        this.$message.error("文件大小不能超过52M");

        return false;
      }
      this.isUploadFile = true;
    },
    uploadSuccess() {
      this.$message.success("添加成功！");
      // 隐藏添加用户的对话框
      this.addDialogVisible = false;
      // 重新获取用户列表数据
      this.$message.success("修改项目信息成功");
      this.editDialogVisible = false;
      this.$refs.projectEditFormRef.resetFields();
      this.$bus.$emit("getAchievementList");
    },
    participantInputChange() {
      let cacheData = this.projectAddForm.participant.split("");
      cacheData.forEach((item, index) => {
        if (item === "，") {
          cacheData[index] = ",";
        }
      });
      this.projectAddForm.participant = cacheData.join("");
    },
    // 监听主持人改变事件
    commanderInputChange() {
      // 先变成数组 寻找到中文逗号改变成为英文逗号
      let cacheData = this.projectEditForm.commander.split("");
      // console.log(cacheData.indexOf("a"));
      cacheData.forEach((item, index) => {
        if (item === "，") {
          // console.log(item);
          cacheData[index] = ",";
        }
      });
      this.projectEditForm.commander = cacheData.join("");
      // console.log(this.projectEditForm.commander);
    },
  },
  mounted() {
    this.$bus.$on(
      "handleIsProjectEditDialogVisibleShow",
      this.projectEditDialogVisibleShow
    );
  },
  beforeDestroy() {
    this.$bus.$off("handleIsProjectEditDialogVisibleShow");
  },
  computed: {
    ...mapState(["subject_classificationList", "collegeList"]),
  },
};
</script>

<style lang="less" scoped>
/deep/.el-dialog {
  margin-top: 20px !important;
  margin-bottom: 20px !important;
}
</style>